package com.huqing.icu.rentreport.service.admin.impl;

import com.huqing.icu.SpringBootApplicationContextUtils;
import com.huqing.icu.base.IdReq;
import com.huqing.icu.base.PagingDto;
import com.huqing.icu.client.UserFeignClient;
import com.huqing.icu.inout.resp.user.UserInfoQueryResp;
import com.huqing.icu.rentreport.dao.ReportRecordDao;
import com.huqing.icu.rentreport.dto.ReportRecordDto;
import com.huqing.icu.rentreport.dto.ReportRecordQueryDto;
import com.huqing.icu.rentreport.enums.ReportApproveStatusEnum;
import com.huqing.icu.rentreport.enums.ReportRecordBusTypeEnum;
import com.huqing.icu.rentreport.enums.ReportRecordSourceType;
import com.huqing.icu.rentreport.inout.in.admin.AdminReportRecordApproveReq;
import com.huqing.icu.rentreport.inout.in.admin.AdminReportRecordListQueryReq;
import com.huqing.icu.rentreport.inout.out.admin.AdminReportRecordListQueryResp;
import com.huqing.icu.rentreport.model.ReportRecord;
import com.huqing.icu.rentreport.service.admin.IAdminReportRecordService;
import com.huqing.icu.utils.CopyUtils;
import com.huqing.icu.utils.PageUtils;
import com.huqing.icu.utils.ParamValidateUtils;
import jakarta.annotation.Resource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 后台举报记录实现类
 * @Author huqing
 * @Date 2025/7/6 20:56
 **/
@Service
public class AdminReportRecordServiceImpl implements IAdminReportRecordService {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private ReportRecordDao reportRecordDao;

    /**
     * 查询举报记录列表
     *
     * @param queryReq
     * @return
     */
    @Override
    public PagingDto<AdminReportRecordListQueryResp> queryList(AdminReportRecordListQueryReq queryReq) {
        ReportRecordQueryDto reportRecordQueryDto = CopyUtils.copy(queryReq, ReportRecordQueryDto.class);
        int startIndex = PageUtils.getPageStartIndex(queryReq.getPageIndex(), queryReq.getPageSize());
        reportRecordQueryDto.setStartIndex(startIndex);
        //1、根据条件查询举报记录数量
        Integer count = reportRecordDao.getNumByCondition(reportRecordQueryDto);

        if (count == 0) {
            return new PagingDto<>(Collections.emptyList(), 0, 0);
        }

        //2、根据条件查询举报记录列表
        List<ReportRecordDto> reportRecordList = reportRecordDao.selectByCondition(reportRecordQueryDto);

        List<Long> reporterIdList = reportRecordList.stream().map(ReportRecordDto::getReporterId).distinct().collect(Collectors.toList());
        List<Long> toIdList = reportRecordList.stream().map(ReportRecordDto::getToId).distinct().collect(Collectors.toList());

        IdReq idReq = new IdReq();
        idReq.setIdList(reporterIdList);
        //3.1 通过feign去调用举报人和被举报人的信息
        List<UserInfoQueryResp> reporterUserList = userFeignClient.queryList(idReq);
        //List<UserInfoQueryResp> reporterUserList = new ArrayList<>();
        idReq.setIdList(toIdList);
        List<UserInfoQueryResp> toUserList = userFeignClient.queryList(idReq);
        //List<UserInfoQueryResp> toUserList = new ArrayList<>();

        Map<Long, UserInfoQueryResp> reporterUserMap = null;
        if (CollectionUtils.isNotEmpty(reporterUserList)) {
            reporterUserMap = reporterUserList.stream().collect(Collectors.toMap(UserInfoQueryResp::getUserId, p -> p));
        }
        Map<Long, UserInfoQueryResp> toUserMap = null;
        if (CollectionUtils.isNotEmpty(toUserList)) {
            toUserMap = toUserList.stream().collect(Collectors.toMap(UserInfoQueryResp::getUserId, p -> p));
        }

        List<AdminReportRecordListQueryResp> respList = CopyUtils.copyOriginListToDestList(reportRecordList, AdminReportRecordListQueryResp.class);

        //4、遍历集合，填充数据
        for (AdminReportRecordListQueryResp resp : respList) {

            //举报人信息
            if (reporterUserMap != null && reporterUserMap.containsKey(resp.getReporterId())) {
                UserInfoQueryResp reporter = reporterUserMap.get(resp.getReporterId());
                resp.setReporterNickname(reporter.getNickname());
            }

            //被举报人信息
            if (toUserMap != null && toUserMap.containsKey(resp.getToId())) {
                UserInfoQueryResp toUser = toUserMap.get(resp.getToId());
                resp.setToNickname(toUser.getNickname());
            }
        }
        return new PagingDto<>(respList, PageUtils.getTotalPage(count, queryReq.getPageSize()), count);
    }

    @Override
    public Integer batchApprove(AdminReportRecordApproveReq approveReq, Long userId) {
        for (Long id : approveReq.getIdList()) {
            SpringBootApplicationContextUtils.getBean(IAdminReportRecordService.class).approveOne(id, approveReq.getApproveStatus(), approveReq.getReason(), userId);
        }
        return 1;
    }

    /**
     * 审核单个
     *
     * @param id
     * @param approveStatus
     * @param reason
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer approveOne(Long id, Integer approveStatus, String reason, Long userId) {

        //1、查询这个举报记录
        ReportRecord reportRecord = reportRecordDao.selectById(id);
        if (reportRecord == null) {
            ParamValidateUtils.throwObjectNotExistExp("举报记录不存在，请检查");
        }

        //如果审核前和审核后的状态是一样的
        if (reportRecord.getApproveStatus().equals(approveStatus)) {
            ParamValidateUtils.throwInternalErrorExp("不能重复审核");
        }

        //修改审核状态
        reportRecord.setApproveTime(new Timestamp(System.currentTimeMillis()));
        reportRecord.setApproveStatus(approveStatus);
        reportRecord.setReason(reason);
        reportRecord.setOperatorId(userId);
        reportRecordDao.updateById(reportRecord);

        //2、如果是审核通过，则要删除对应的业务，比如删除帖子、删除房源等
        if (ReportApproveStatusEnum.PASS.getCode().equals(approveStatus)) {

            //kafka发送消息，删除房源、社区帖子、评论
            kafkaSendDeleteMessage(reportRecord);
        }
        return 1;
    }

    @Override
    public Integer testKafka() {
        kafkaTemplate.send("huqingTopic", "123");
        return 1;
    }

    /**
     * kafka发送消息，删除房源、社区帖子、评论
     *
     * @param reportRecord
     * @return
     */
    private Integer kafkaSendDeleteMessage(ReportRecord reportRecord) {

        //如果是举报业务本身
        if (ReportRecordSourceType.THIS.getCode().equals(reportRecord.getSourceType())) {

            //如果是举报房源
            if (ReportRecordBusTypeEnum.HOUSE.getCode().equals(reportRecord.getBusType())) {
                //kafka发送消息，下架房源
                kafkaTemplate.send("downHouseByReport", reportRecord.getBusId());
            } else if (ReportRecordBusTypeEnum.COMMUNITY_POST.getCode().equals(reportRecord.getBusType())) {

                //如果是举报社区帖子
                //kafka发送消息，下架帖子
                kafkaTemplate.send("downPostByReport", reportRecord.getBusId());
            } else if (ReportRecordBusTypeEnum.COMMENT.getCode().equals(reportRecord.getBusType())) {
                //如果是举报评论
                //kafka发送消息，删除评论
                kafkaTemplate.send("deletePostByComment", reportRecord.getSourceId());
            }
        } else if (ReportRecordSourceType.COMMENT.getCode().equals(reportRecord.getSourceType())) {
            //如果是举报评论
            //kafka发送消息，删除评论
            kafkaTemplate.send("deletePostByComment", reportRecord.getSourceId());
        }
        return 1;
    }
}
